package queue;


import java.util.Scanner;

/** 数组模拟缓刑队列 */
public class CircleArrayQueueDemo {

  public static void main(String[] args) {
    CircleArrayQueue arrayQueue = new CircleArrayQueue(4);
    boolean loop = true;
    Scanner scanner = new Scanner(System.in);
    while (loop) {
      System.out.println("a:添加队列");
      System.out.println("g:出队列");
      System.out.println("s:显示队列");
      System.out.println("h:队头");
      System.out.println("e:退出");
      char opt = scanner.next().charAt(0);
      switch (opt) {
        case 'a':
          System.out.println("输入一个数字：");
          int value = scanner.nextInt();
          arrayQueue.add(value);
          break;
        case 'g':
          try {
            System.out.println(arrayQueue.getQueue());
          } catch (Exception e) {
            e.printStackTrace();
          }
          break;
        case 's':
          arrayQueue.showQueue();
          break;
        case 'h':
          try {
            arrayQueue.queueHead();
          } catch (Exception e) {
            e.printStackTrace();
          }
          break;
        case 'e':
          loop = false;
          break;
          default: break;
      }
    }
  }
}

class CircleArrayQueue {

  private int maxSize;
  private int front;
  private int rear;
  private int[] array;

  public CircleArrayQueue(int maxSize) {
    this.maxSize = maxSize;
    array = new int[maxSize];
  }

  // 判断队满
  public boolean isFull() {
    return (rear+1)%maxSize==front;
  }

  // 判断队空
  public boolean isEmpty() {
    return front == rear;
  }

  // 入队
  public void add(int data) {
    if (isFull()) {
      System.out.println("队满，无法添加！");
      return;
    }
    array[rear]=data;
    rear=(rear+1)%maxSize;
  }

  // 出队列
  public int getQueue() {
    if (isEmpty()) {
      throw new RuntimeException("队列为空");
    }
    int value = array[front];
    front=(front+1)%maxSize;
    return value;
  }

  // 显示队列
  public void showQueue() {
    if (isEmpty()) {
      System.out.println("队列为空！");
      return;
    }
    for (int i = front; i < front+ (rear-front+maxSize)%maxSize; i++) {
      System.out.printf("array[%d]=%d ",i%maxSize,array[i%maxSize]);
    }
    System.out.println();
  }

  // 队头
  public void queueHead() {
    if (isEmpty()) {
      throw new RuntimeException("队列为空1");
    }
    System.out.println("队头：" + array[front]);
  }
}
